﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Multiple database support | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Multiple database support | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.0.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="multiple-database-support">Multiple database support</h1>

<p>you can store and retrieve Entities in multiple databases on either a single server or multiple servers. the only requirement is to have unique names for each database. the following example demonstrates how to use multiple databases.</p>
<h3 id="usage-example">Usage example:</h3>
<p>use the <code>DB.DatabaseFor&lt;T&gt;()</code> method to specify which database you want the Entities of a given type to be stored in. it is only neccessary to do that for the entities you want to store in a non-default database. the default database is the very first database your application initializes. all entities by default are stored in the default database unless specified otherwise using <code>DatabaseFor</code>.</p>
<p>as such, the <code>Book</code> entities will be stored in the &quot;BookShop&quot; database and the <code>Picture</code> entities are stored in the &quot;BookShopFILES&quot; database considering the following code.</p>
<pre><code class="lang-csharp">await DB.InitAsync(&quot;BookShop&quot;);
await DB.InitAsync(&quot;BookShopFILES&quot;);

DB.DatabaseFor&lt;Picture&gt;(&quot;BookShopFILES&quot;);

var book = new Book { Title = &quot;Power Of Now&quot; };
await book.SaveAsync();
//alternative:
//// await DB.SaveAsync(book);

var pic = new Picture
{
    BookID = book.ID,
    Name = &quot;Power Of Now Cover Photo&quot;
};

await pic.SaveAsync();
//alternative:
//// await DB.SaveAsync(pic);

await DB.Update&lt;Picture&gt;()
        .Match(p =&gt; p.ID == pic.ID)
        .Modify(p =&gt; p.Name, &quot;Updated Cover Photo&quot;)
        .ExecuteAsync();

var result = await DB.Find&lt;Picture&gt;().OneAsync(pic.ID);                    
</code></pre>
<div class="NOTE">
<h5>Note</h5>
<p>an entity type is tied to a specific database by calling the <strong>DatabaseFor</strong> method with the database name on startup. that entity type will always be stored in and retrieved from that specific database only. it is not possible to save a single entity type in multiple databases.</p>
</div>
<p>if you prefer to keep your database specifications inside the entity classes themselves, you could even call <code>DatabaseFor</code> in the static constructor like so:</p>
<pre><code class="lang-csharp">public class Picture : Entity
{
    static Picture() =&gt; DB.DatabaseFor&lt;Picture&gt;(&quot;BookShopFILES&quot;);
}
</code></pre>
<h3 id="limitations">Limitations</h3>
<ul>
<li>cross-database relationships with <code>Many&lt;T&gt;</code> is not supported.</li>
<li>no cross-database joins/ look-ups as the driver doesn't support it.</li>
<li>storing a single entity type in multiple datbases is not supported.</li>
</ul>
<h2 id="utility-methods">Utility methods</h2>
<h3 id="get-database-name-from-an-entity-instance-or-type">Get database name from an entity instance or type</h3>
<pre><code class="lang-csharp">var dbName = pic.DatabaseName();
var dbName = DB.DatabaseName&lt;Book&gt;();
</code></pre>
<p>the above methods will return the name of the database that the entity is stored in. if not specifically attached to seperate db, it will return the name of the default database.</p>
<h3 id="check-if-a-database-already-exists-on-the-server">Check if a database already exists on the server</h3>
<pre><code class="lang-csharp">bool dbExists = await DB.Database(&quot;BookShopFILES&quot;).ExistsAsync();
bool dbExists = await DB.Database&lt;Picture&gt;().ExistsAsync();
</code></pre>
<h3 id="check-if-a-database-is-still-accessible">Check if a database is still accessible</h3>
<pre><code class="lang-csharp">bool isAlive = await DB.Database(&quot;BookShopFILES&quot;).IsAccessibleAsync();
bool isAlive = await DB.Database&lt;Picture&gt;().IsAccessibleAsync();
</code></pre>
<h3 id="get-a-list-of-all-databases-on-the-server">Get a list of all databases on the server</h3>
<pre><code class="lang-csharp">var dbNames = await DB.AllDatabaseNamesAsync(&quot;localhost&quot;);
</code></pre>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
